package com.pm.utils;

import com.pm.common.Response;
import com.pm.common.exception.ExpCodeState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class UploadImageUtils {
    private static final Logger logger = LoggerFactory.getLogger(UploadImageUtils.class);

    public static Response<String> uploadImages(MultipartFile filedata, HttpServletRequest request) {
        Response<String> response = null;
        //判断传递图片数据是否为空
        if (filedata.isEmpty()) {
            response = new Response<String>(ExpCodeState.upload_equip_image_failed);
            return response;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(new Date());
        // 上传的文件名
        String oldName = filedata.getOriginalFilename();
        //图片访问URI(即除了协议、地址和端口号的URL)
        String filePath = System.getProperty("user.dir") + "/src/main/resources/uploadEquipImage/";
        String savePath = filePath;

        File file = new File(savePath);
        if (!file.exists() || !file.isDirectory()) {
            file.mkdirs();
        }
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            File newFile = new File(filePath + newName);
            filedata.transferTo(newFile);
            //数据备份
            File copydata = new File(System.getProperty("user.dir") + "/" + format + "/" + newName);
            filedata.transferTo(copydata);
            response = new Response<String>(ExpCodeState.upload_equip_image_success, newName);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            response = new Response<String>(ExpCodeState.upload_equip_image_failed);
        }
        return response;
    }

}
